package httpUtil

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
)

func HttpPost(url, s string) (res string, err error) {
	resp, err := http.Post(url, "application/json", strings.NewReader(s))
	if err != nil {
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
		}
	}(resp.Body)

	res, _ = getBodyString(resp.Body)
	return
}

func HttpGet(url string) (res string, err error) {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	if resp.StatusCode != 200 {
		return "", errors.New("请求失败")
	}

	res, err = getBodyString(resp.Body)
	if err != nil {
		return "", errors.New(fmt.Sprintf("json解析失败：%s", res))
	}

	return
}

func getBodyString(reader io.Reader) (string, error) {
	body, e := ioutil.ReadAll(reader)
	if e != nil {
		return "", e
	}
	return string(body), nil
}
